#include "bsp_adc.h"
#include "adc_config.h"
#include "stm32f4xx_hal.h"

#define CURRENT_RATIO 1.7544f       // 根据运放关系，实际电流与采集到的电压系数为 1A : 0.57V
#define PUSHROD_V_RATIO 16.0f       // 根据分压关系，推杆主电压与采集到的电压系数为 16V : 1V
#define SYSTEM_MAIN_V_RATIO 16.0f   // 根据分压关系，系统主电压与采集到的电压系数为 16V : 1V
#define SYSTEM_5V_RATIO 2.0f        // 根据分压关系，系统5V电压与采集到的电压系数为 2V : 1V

volatile float ADC_raw_voltage[ADC_GROUP1_TOTAL_CHANNEL]; // unit: mV

static const float VOLTAGE_RATIO = 3300.0 / 4096.0;
/**
 * @brief 获取ADC采集到的原始电压值
 * 
 */
void ADC_getRawVoltageFloat(void)
{
    ADC_raw_voltage[0] = (ADC_convert_value[0] * VOLTAGE_RATIO);
    ADC_raw_voltage[1] = (ADC_convert_value[1] * VOLTAGE_RATIO);
    ADC_raw_voltage[2] = (ADC_convert_value[2] * VOLTAGE_RATIO);
    ADC_raw_voltage[3] = (ADC_convert_value[3] * VOLTAGE_RATIO);
}

/**
 * @brief This function handles DMA2 stream0 global interrupt.
 * 4个通道采样全部采样完毕后进入中断，根据配置，中断频率大约5kHz
 */
void DMA2_Stream0_IRQHandler(void)
{
    HAL_DMA_IRQHandler(&hdma_adc1);
    ADC_getRawVoltageFloat();
}

/**
 * @brief ADC采集到的原始电压值转换为对应的实际物理量
 */

/**
 * @brief Get the Pushrod Current object
 * 
 * @return float 单位mA;
 */
float getPushrodMotorCurrent(void)
{
    return (ADC_raw_voltage[0] * CURRENT_RATIO);
}

/**
 * @brief Get the Pushrod Main Voltage object
 * 
 * @return float 单位mV;
 */
float getPushrodMainVoltage(void)
{
    return (ADC_raw_voltage[1] * PUSHROD_V_RATIO);
}

/**
 * @brief Get the Servo Motor Voltage object
 * 
 * @return float 单位mV;
 */
float getSystemPowerVoltage(void)
{
    return (ADC_raw_voltage[2] * SYSTEM_MAIN_V_RATIO);
}

/**
 * @brief Get the Shoes Voltage object
 * 
 * @return float 单位mV;
 */
float getSystem5vVoltage(void)
{
    return (ADC_raw_voltage[3] * SYSTEM_5V_RATIO);
}

